/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package ru.ssau.managed;

import java.io.Serializable;
import java.util.*;
import javax.ejb.EJB;
import javax.enterprise.context.SessionScoped;
import javax.inject.Named;
import ru.ssau.datamanager.DataManager;
import ru.ssau.entities.AuthorizationInfo;
import ru.ssau.entities.DataAccessException;
import ru.ssau.entities.User;

@Named("user")
@SessionScoped
public class UserBean implements Serializable {

    public static final String ADD = "Add user";
    public static final String EDIT = "Edit user";
    public static final String NO_USER_TO_EDIT = "noUserToEdit";
    public static final String VIEW = "View";
    public static final String SEARCH = "Search users";

    @EJB
    private DataManager dataManager;

    private String searchParameter;
    private Integer selectedUserId;
    private User currentUser;
    private Boolean setCurrentDate;
    private String action;

    List<User> searchResult;

    public UserBean() {

    }

    public String getName() {
        if(currentUser == null) return null;
        return currentUser.getName();
    }

    public void setName(String name) {
        currentUser.setName(name);
    }

    public String getInfo() {
        if(currentUser == null) return null;
        return currentUser.getInfo();
    }

    public void setInfo(String info) {
        currentUser.setInfo(info);
    }

    public String getLogin() {
        if(currentUser == null) return null;
        return currentUser.getAuthorizationInfo().getLogin();
    }

    public void setLogin(String login) {
        currentUser.getAuthorizationInfo().setLogin(login);
    }

    public String getPassword() {
        if(currentUser == null) return null;
        return currentUser.getAuthorizationInfo().getPassword();
    }

    public void setPassword(String password) {
        currentUser.getAuthorizationInfo().setPassword(password);
    }

    public Date getRegistrationDate() {
        if(currentUser == null) return null;
        return currentUser.getRegistrationDate();
    }

    public void setRegistrationDate(Date date) {
        if(setCurrentDate) {
            date = new Date();
        }
        currentUser.setRegistrationDate(date);
    }

    //Получение параметра поиска (в окне поиска
    //каждый раз устанавливается пустое значение)
    public String getSearchParameter() {
        return "";
    }

    public void setSearchParameter(String searchParameter) {
        this.searchParameter = searchParameter;
    }

    //Формирование списка пользователей для отображения
    public Map<String, Integer> getAllUsers() throws DataAccessException {
        Collection<User> users = dataManager.getAllUsers();
        Map<String, Integer> userMap = new LinkedHashMap<String, Integer>();
        
        for(User user: users) {
            String description = String.format("%d. %s", user.getId(), user.getName());
            userMap.put(description, user.getId());
        }
        if(userMap.size() < 1) {
            currentUser = null;
        }

        return userMap;
    }

    //id текущего пользователя (того, который выбран для отображения)
    public Integer getSelectedUserId() {
        return selectedUserId;
    }

    public void setSelectedUserId(Integer selectedUserId) {
        this.selectedUserId = selectedUserId;
    }

    //Флаг, говорящий о том, что в качестве даты регистрации
    //пользователя устанавливается текущая дата
    public Boolean getSetCurrentDate() {
        return setCurrentDate;
    }

    public void setSetCurrentDate(Boolean setCurrentDate) {
        this.setCurrentDate = setCurrentDate;
    }

    public void search() throws DataAccessException {
        Collection<User> foundUsers = dataManager.findUsersByName(searchParameter);
        searchResult = new LinkedList<User>(foundUsers);
        action = SEARCH;
    }

    public List<User> getSearchResult() {
        return searchResult;
    }

    public String getAction() {
        return action;
    }

    public void doAction() throws DataAccessException {
        if(action.equals(ADD)) {
            add();
        } else {
            edit();
        }
        selectedUserId=null;
        action = VIEW;
    }

    public void add() throws DataAccessException {
        dataManager.addUser(currentUser);
    }

    public void edit() throws DataAccessException {
        dataManager.replaceUser(currentUser);
    }

    //Удаление сущности
    public void delete() throws DataAccessException {
        dataManager.deleteUserById(selectedUserId);
        action = VIEW;
        currentUser = null;
    }

    //Удаление сущности из списка найденных
    public void deleteFromSearchResult(User user) throws DataAccessException {
        dataManager.deleteUserById(user.getId());
        searchResult.remove(user);
        action = null;
    }

    public void editFromSearchResult(User user) {
        currentUser = user;
        action = EDIT;
    }

    public void setCurrentUser() throws DataAccessException {
        currentUser = dataManager.getUserById(selectedUserId);
    }

    public void ensureCurrentUserSet() throws DataAccessException {
        if(currentUser == null) {
            action = NO_USER_TO_EDIT;
        } else {
            //work around-ец. Снова.
            if(currentUser.getId() == null) {
                currentUser = dataManager.getUserById(selectedUserId);
                if(currentUser == null) {
                    action = NO_USER_TO_EDIT;
                } else {
                    setCurrentDate = false;
                    action = EDIT;
                }
            } else {
                setCurrentDate = false;
                action = EDIT;
            }
        }
    }

    public void unsetCurrentUser() {
        currentUser = new User();
        currentUser.setAuthorizationInfo(new AuthorizationInfo());
        setCurrentDate = true;
        action = ADD;
    }
}